// AccountManagement.tsx
import React, { useState, useEffect } from 'react';
import { Input, Button, Table, Modal, Form, message, Space } from 'antd';
import type { FormInstance } from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { AccountType } from '../../types'; // 假设你已经定义了这个类型
import { addAccount, deleteAccount, queryAccounts, UpdateOtherPassword, updatePassword } from '../../service'; // 假设你已经定义了这些服务函数
import PermissionAdd, { PermissionAddParam } from '../../components/dialog/GrantPerm';

export const Account: React.FC = () => {
  const [searchUsername, setSearchUsername] = useState<string>('');
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>('');
  const [currentAccount, setCurrentAccount] = useState<AccountType>({ id: 0, username: '', password: '' });
  const [form] = Form.useForm<AccountType>();
  const [accounts, setAccounts] = useState<AccountType[]>([]);
  const [permissionAddParam, setPermissionAddParam] = useState<PermissionAddParam>(null);

  
  useEffect(() => {
    queryAccounts({}).then((x) => {
      setAccounts(x.data);
    });
  }, []);

  const handleSearch = () => {
    if (!searchUsername) {
      message.warning('请输入用户名');
      return;
    }
    const filteredAccounts = accounts.filter((account) =>
      account.username.toLowerCase().includes(searchUsername.toLowerCase())
    );
    setAccounts(filteredAccounts);
  };

  const handleResetSearch = () => {
    setSearchUsername('');
    queryAccounts({}).then((x) => {
      setAccounts(x.data);
    });
  };

  const handleAdd = () => {
    setModalTitle('新建账号');
    form.setFieldsValue({ id: 0, username: '', password: '' });
    setCurrentAccount({ id: 0, username: '', password: '' });
    setIsModalOpen(true);
  };

  const handleEdit = (record: AccountType) => {
    setModalTitle('编辑账号');
    form.setFieldsValue(record);
    setCurrentAccount(record);
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteAccount({
        id: id,
      });
      const newAccounts = accounts.filter((account) => account.id !== id);
      setAccounts(newAccounts);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };
  const handlePerm = async (id: number) => {
    try {
      const account1 = accounts.filter((account) => account.id == id)[0];
      console.log("account1account1",account1)
      setPermissionAddParam({username:account1.username})
    } catch (error) {
    }
  };
  const onSubmit = async (values: AccountType) => {
    if (currentAccount.id === 0) {
      // 新建账号
      try {
        const rsp = await addAccount(values);
        queryAccounts({}).then((x) => {
          setAccounts(x.data);
        });
        message.success('新建成功');
      } catch (error) {
        message.error('新建失败');
      }
    } else {
      // 编辑账号
      try {
        await UpdateOtherPassword({username:values.username,password:values.password});
        const newAccounts = accounts.map((account) =>
          account.id === currentAccount.id ? { ...account, ...values } : account
        );
        setAccounts(newAccounts);
        message.success('编辑成功');
      } catch (error) {
        message.error('编辑失败');
      }
    }
    setIsModalOpen(false);
  };

  const handleModalOk = async () => {
    form.submit();
  };

  const handleModalCancel = () => {
    setIsModalOpen(false);
  };

  const columns: ColumnsType<AccountType> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      render:(x)=>{
        return "*********"
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleDelete(record.id)}>
            删除
          </Button>

          <Button type="link" onClick={() => handlePerm(record.id)}>
            权限管理
          </Button>
          
        </div>
      ),
    },
  ];

  return (
    <div className='w-full p-8'>
      {permissionAddParam && <PermissionAdd visible={permissionAddParam != null} params={permissionAddParam} onClose={function (): void {
        setPermissionAddParam(null)
      } } />
      }
      <div style={{ marginBottom: 16 }}>
        <Space className='flex justify-end'>
          <Input
            placeholder="请输入用户名"
            value={searchUsername}
            onChange={(e) => setSearchUsername(e.target.value)}
            style={{ width: 200, marginRight: 8 }}
          />
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleResetSearch}>重置</Button>
          <Button type="primary" onClick={handleAdd}>
            新建账号
          </Button>
        </Space>
      </div>
      <Table<AccountType>
        columns={columns}
        dataSource={accounts}
        rowKey="id"
      />
      <Modal
        title={modalTitle}
        open={isModalOpen}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <Form form={form} initialValues={currentAccount} onFinish={onSubmit}>
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};